<!--
 * @LastEditTime: 2024-09-07 11:48:27
 * @Description: 
 * @Date: 2024-08-28 02:28:06
 * @Author: wangshan
 * @LastEditors: wangshan
-->
<template>
  <div class="richText">
    <Toolbar
      class="tool-bar"
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="data.toolbarConfig"
      mode="default"
    />
    <Editor
      style="height: 450px; overflow-y: hidden"
      v-model="data.valueHtml"
      :defaultConfig="data.editorConfig"
      mode="default"
      @onCreated="handleCreated"
      @onChange="handleChange"
      @onDestroyed="handleDestroyed"
      @onFocus="handleFocus"
      @onBlur="handleBlur"
    />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import {
  reactive,
  shallowRef,
  onMounted,
  onBeforeUnmount,
  watchEffect,
  defineEmits
} from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { sendFile } from '@/api/common/common.js'
// import { ossFileUpload } from '@/api/uploadFile'
import { ElMessage } from 'element-plus'

onMounted(() => {
  watchEffect(() => {
    if (props.value) {
      data.valueHtml = props.value || ''
    } else {
      data.valueHtml = ''
    }
  })
})

onBeforeUnmount(() => {
  // 组件销毁时，也及时销毁编辑器
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const emit = defineEmits(['update:value'])

const props = defineProps({
  toolbarConfig: { type: Object },
  editorConfig: { type: Object },
  value: { type: String }
})

const data = reactive({
  toolbarConfig: {
    // 工具栏排除的工具项配置
    excludeKeys: ["uploadVideo", // 排除菜单组，写菜单组 key 的值即可
    "group-video"]
    // 工具栏所有可用配置：'bold','underline','italic','through','code','clearStyle','headerSelect','header1','header2',
    // 'header3','color','bgColor','insertLink','editLink','unLink','viewLink','insertImage','deleteImage','editImage',
    // 'viewImageLink','imageWidth30','imageWidth50','imageWidth100','blockquote','emotion','fontSize','fontFamily',
    // 'indent','delIndent','justifyLeft','justifyRight','justifyCenter','lineHeight','redo','undo','divider','codeBlock',
    // 'bulletedList','numberedList','insertTable','deleteTable','insertTableRow','deleteTableRow','insertTableCol',
    // 'deleteTableCol','tableHeader','tableFullWidth','insertVideo','deleteVideo','uploadImage','codeSelectLang'
  },
  editorConfig: props.editorConfig || {
    MENU_CONF: {},
    placeholder: '请输入'
  },
  templateContent: '',
  valueHtml: props.value
})

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 编辑器回调函数
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
const handleChange = (editor) => {
  data.templateContent = editor.getHtml()
  emit('update:value', data.valueHtml)
}
const handleDestroyed = (editor) => {
  // console.log('destroyed', editor)
}
const handleFocus = (editor) => {
  // console.log('focus', editor)
}
const handleBlur = (editor) => {
  // console.log('blur', editor)
}
const uploadFle = async (file, insert) => {
  try {
    const forms = new FormData()
    forms.append('file', file)
    const res = await sendFile(forms)
    if(res.code === 200) {
      
       ElMessage({
          type: 'success',
          message: '上传成功'
      })
      insert(res.url, res.originalFilename, res.url)
    }
  } catch (error) {
    console.log('====================================');
    console.log('hello=========', error);
    console.log('====================================');
  }
}
data.editorConfig.MENU_CONF.uploadImage = {
  // 自定义图片上传
  async customUpload(file, insertFn) {
      // file 即选中的文件
      // 自己实现上传（可使用阿里云的oss实现），并得到图片 url alt href
      // 最后插入图片
      uploadFle(file,insertFn)
  }
}

data.editorConfig.MENU_CONF.uploadVideo = {
  // 自定义视频上传
  async customUpload(file, insertFn) {
      //file 即选中的文件
      // 自己实现上传（可使用阿里云的oss实现），并得到视频 url poster
      // 最后插入视频
      // insertFn(url, poster || '')
      uploadFle(file,insertFn)
  }
}
</script>
